﻿/*
**  2D向量
*/
if(!$.Engine.Math || typeof $.Engine.Math === "undefined") $.Engine.Math = {};
if (!$.Engine.Math.Vector2D || typeof $.Engine.Math.Vector2D === "undefined")
  $.Engine.Math.Vector2D = function (x_, y_) { this.x = x_; this.y = y_; };
Object.extend($.Engine.Math.Vector2D.prototype, {
  Set: function (x_, y_) { this.x = x_; this.y = y_; return this; },
  SetV: function (v) { this.Set(v.x, v.y); return this; },
  Add: function (v) { this.x += v.x; this.y += v.y; return this; },
  Subtract: function (v) { this.x += v.x; this.y += v.y; return this; },
  Multiply: function (a) { this.x *= a; this.y *= a; return this; },
  //向量乘矩阵
  MulM: function (A) {
    var tX = this.x;
    this.x = A.col1.x * tX + A.col2.x * this.y;
    this.y = A.col1.y * tX + A.col2.y * this.y;
    return this;
  },
  MulTM: function (A) {
    var tX = $.Engine.Math.Dot(this, A.col1);
    this.y = $.Engine.Math.Dot(this, A.col2);
    this.x = tX;
    return this;
  },
  Negative: function () { return new $.Engine.Math.Vector2D(-this.x, -this.y); },
  Copy: function () { return new $.Engine.Math.Vector2D(this.x, this.y); },
  CrossVF: function (s) {
    var tX = this.x;
    this.x = s * this.y;
    this.y = -s * tX;
  },

  CrossFV: function (s) {
    var tX = this.x;
    this.x = -s * this.y;
    this.y = s * tX;
  },

  MinV: function (b) {
    this.x = this.x < b.x ? this.x : b.x;
    this.y = this.y < b.y ? this.y : b.y;
  },

  MaxV: function (b) {
    this.x = this.x > b.x ? this.x : b.x;
    this.y = this.y > b.y ? this.y : b.y;
  },

  Abs: function () {
    this.x = Math.abs(this.x);
    this.y = Math.abs(this.y);
  },

  Length: function () {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  },

  Normalize: function () {
    var length = this.Length();
    if (length < Number.MIN_VALUE) {
      return 0.0;
    }
    var invLength = 1.0 / length;
    this.x *= invLength;
    this.y *= invLength;

    return length;
  },

  IsValid: function () {
    return $.Engine.Math.IsValid(this.x) && $.Engine.Math.IsValid(this.y);
  },

  Make: function (x_, y_) {
    return new $.Engine.Math.Vector2D(x_, y_);
  },

  x: null,
  y: null
});